package com.diggerh.ch6asynctask.p1simpletask;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * @author diggerH
 * @date 2022-11-25
 */
@Slf4j
@Service
public class AsyncTaskService1 {
    public static final Random RANDOM = new Random();
    public static final int MAX_RANDOM_TIME_MILLIS = 10000;

    @Async
    public CompletableFuture<String> doTask1() throws Exception {
        int taskId = 1;
        return doTask(taskId);
    }

    @Async
    public CompletableFuture<String> doTask2() throws Exception {
        int taskId = 2;
        return doTask(taskId);
    }

    @Async
    public CompletableFuture<String> doTask3() throws Exception {
        int taskId = 3;
        return doTask(taskId);
    }

    public CompletableFuture<String> doTask(int taskId) throws Exception {
        long threadId = Thread.currentThread().getId();
        log.info("threadId:{}, task {} begin ...", threadId, taskId);
        long start = System.currentTimeMillis();
        Thread.sleep(RANDOM.nextInt(MAX_RANDOM_TIME_MILLIS));
        long end = System.currentTimeMillis();
        log.info("threadId:{}, task {} used：{} millis.", threadId, taskId, end - start);
        return CompletableFuture.completedFuture("threadId:" + threadId + ", task " + taskId + " completed.");
    }
}
